<template>
  <div class="attribute-management page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">属性管理</h1>
        <p class="page-subtitle">
          管理系统属性信息，支持销售属性、关键属性、普通属性管理
        </p>
      </div>
      <el-button type="primary" @click="openAddDialog" class="add-btn">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
        </svg>
        新增属性
      </el-button>
    </div>

    <div class="content-card">
      <div class="search-section">
        <el-input
          v-model="searchForm.name"
          placeholder="搜索属性名称"
          class="search-input"
          clearable
        >
          <template #prefix>
            <svg class="search-icon" viewBox="0 0 24 24" fill="currentColor">
              <path
                d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"
              />
            </svg>
          </template>
        </el-input>
        <el-select
          v-model="searchForm.type"
          placeholder="选择属性类型"
          clearable
          class="type-select"
        >
          <el-option label="销售属性" :value="1" />
          <el-option label="关键属性" :value="2" />
          <el-option label="普通属性" :value="3" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <el-table
        :data="attributeList"
        style="width: 100%"
        class="attribute-table"
        v-loading="loading"
        :cell-style="{ paddingLeft: '20px' }"
        :header-cell-style="{ paddingLeft: '20px' }"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="name"
          label="属性名称"
          width="150"
          min-width="200"
        />
        <el-table-column prop="type" label="属性类型" width="120">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)" size="small">
              {{ getTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="inputType" label="输入类型" width="120">
          <template #default="scope">
            <el-tag
              :type="getInputTypeTagType(scope.row.inputType)"
              size="small"
            >
              {{ getInputTypeLabel(scope.row.inputType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="values" label="可选值" width="240">
          <template #default="scope">
            <div class="values-display">
              <el-tag
                v-for="value in scope.row.valueList"
                :key="value"
                size="small"
                type="info"
                class="value-tag"
              >
                {{ value }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="isRequired" label="是否必填" width="100">
          <template #default="scope">
            <el-tag
              :type="scope.row.isRequired === 1 ? 'danger' : 'info'"
              size="small"
            >
              {{ scope.row.isRequired === 1 ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="modifiedByName" label="修改人" width="200" />
        <el-table-column prop="modifiedTime" label="修改时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="openEditDialog(scope.row)"
              class="action-btn"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteAttribute(scope.row)"
              class="action-btn"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增属性' : '编辑属性'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="attribute-form"
      >
        <el-form-item label="属性名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入属性名称" />
        </el-form-item>

        <el-form-item label="属性类型" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择属性类型"
            style="width: 100%"
          >
            <el-option label="销售属性" :value="1" />
            <el-option label="关键属性" :value="2" />
            <el-option label="普通属性" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="输入类型" prop="inputType">
          <el-select
            v-model="form.inputType"
            placeholder="请选择输入类型"
            style="width: 100%"
          >
            <el-option label="手工输入" :value="1" />
            <el-option label="单选" :value="2" />
            <el-option label="多选" :value="3" />
          </el-select>
        </el-form-item>

        <el-form-item label="可选值" prop="values">
          <el-input
            v-model="form.values"
            type="textarea"
            :rows="4"
            placeholder="请输入可选值，多个值用(英文)逗号分隔"
          />
          <div class="form-tip">如：红色,蓝色,绿色</div>
        </el-form-item>

        <el-form-item label="是否必填" prop="isRequired">
          <el-radio-group v-model="form.isRequired">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAttribute" :loading="saving">
            {{ dialogType === "add" ? "新增" : "保存" }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { postWithAuth } from "@/utils/request";

// 类型定义
interface AttributeDTO {
  id?: string;
  name: string;
  type: number;
  inputType: number;
  values: string;
  valueList?: string[];
  isRequired: number;
  sort: number;
  createdBy?: string;
  createdByName?: string;
  createdTime?: string;
  modifiedBy?: string;
  modifiedByName?: string;
  modifiedTime?: string;
}

interface SearchForm {
  name: string;
  type: number | null;
}

interface Pagination {
  pageIndex: number;
  pageSize: number;
  total: number;
}

// 响应式数据
const loading = ref(false);
const saving = ref(false);
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const attributeList = ref<AttributeDTO[]>([]);
const formRef = ref();

// 搜索表单
const searchForm = reactive<SearchForm>({
  name: "",
  type: null,
});

// 分页
const pagination = reactive<Pagination>({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});

// 表单数据
const form = reactive<AttributeDTO>({
  name: "",
  type: 1,
  inputType: 1,
  values: "",
  isRequired: 0,
  sort: 0,
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入属性名称", trigger: "blur" },
    {
      min: 1,
      max: 50,
      message: "属性名称长度在 1 到 50 个字符",
      trigger: "blur",
    },
  ],
  type: [{ required: true, message: "请选择属性类型", trigger: "change" }],
  inputType: [{ required: true, message: "请选择输入类型", trigger: "change" }],
  sort: [{ required: true, message: "请输入排序值", trigger: "blur" }],
};

// 获取属性类型标签
const getTypeLabel = (type: number): string => {
  const typeMap: Record<number, string> = {
    1: "销售属性",
    2: "关键属性",
    3: "普通属性",
  };
  return typeMap[type] || "未知";
};

// 获取属性类型标签样式
const getTypeTagType = (type: number): string => {
  const typeMap: Record<number, string> = {
    1: "success",
    2: "warning",
    3: "info",
  };
  return typeMap[type] || "info";
};

// 获取输入类型标签
const getInputTypeLabel = (inputType: number): string => {
  const inputTypeMap: Record<number, string> = {
    1: "手工输入",
    2: "单选",
    3: "多选",
  };
  return inputTypeMap[inputType] || "未知";
};

// 获取输入类型标签样式
const getInputTypeTagType = (inputType: number): string => {
  const inputTypeMap: Record<number, string> = {
    1: "info",
    2: "primary",
    3: "warning",
  };
  return inputTypeMap[inputType] || "info";
};

// 获取属性列表
const fetchAttributeList = async () => {
  loading.value = true;
  try {
    const response = await postWithAuth(
      "/internal/attribute/pageListByNameAndType",
      {
        name: searchForm.name,
        type: searchForm.type,
        pageIndex: pagination.pageIndex,
        pageSize: pagination.pageSize,
      }
    );

    if (response.code === 0) {
      attributeList.value = response.data.list;
      pagination.total = parseInt(response.data.total);
    } else {
      ElMessage.error(response.message || "获取属性列表失败");
    }
  } catch (error) {
    console.error("获取属性列表失败:", error);
    ElMessage.error("获取属性列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.pageIndex = 1;
  fetchAttributeList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.name = "";
  searchForm.type = null;
  pagination.pageIndex = 1;
  fetchAttributeList();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.pageIndex = 1;
  fetchAttributeList();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page;
  fetchAttributeList();
};

// 打开新增对话框
const openAddDialog = () => {
  dialogType.value = "add";
  dialogVisible.value = true;
  resetForm();
};

// 打开编辑对话框
const openEditDialog = (row: AttributeDTO) => {
  dialogType.value = "edit";
  dialogVisible.value = true;
  Object.assign(form, {
    id: row.id,
    name: row.name,
    type: row.type,
    inputType: row.inputType,
    values: row.values,
    isRequired: row.isRequired,
    sort: row.sort,
  });
};

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: undefined,
    name: "",
    type: 1,
    inputType: 1,
    values: "",
    isRequired: 0,
    sort: 0,
  });
  formRef.value?.clearValidate();
};

// 保存属性
const saveAttribute = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    saving.value = true;

    const url =
      dialogType.value === "add"
        ? "/internal/attribute/add"
        : "/internal/attribute/modify";

    const response = await postWithAuth(url, form);

    if (response.code === 0) {
      ElMessage.success(dialogType.value === "add" ? "新增成功" : "修改成功");
      dialogVisible.value = false;
      fetchAttributeList();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("保存属性失败:", error);
    ElMessage.error("保存失败");
  } finally {
    saving.value = false;
  }
};

// 删除属性
const deleteAttribute = async (row: AttributeDTO) => {
  try {
    await ElMessageBox.confirm(`确定要删除属性"${row.name}"吗？`, "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await postWithAuth("/internal/attribute/delete", {
      id: row.id,
    });

    if (response.code === 0) {
      ElMessage.success("删除成功");
      fetchAttributeList();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除属性失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchAttributeList();
});
</script>

<style scoped>
.attribute-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  /* background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); */
}

.header-content {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.add-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  font-weight: 500;
}

.btn-icon {
  width: 16px;
  height: 16px;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-section {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 250px;
}

.type-select {
  width: 150px;
}

.search-icon {
  width: 16px;
  height: 16px;
  color: #909399;
}

.attribute-table {
  margin: 0;
}

.values-display {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.value-tag {
  margin: 2px;
}

.action-btn {
  margin-right: 8px;
}

.action-btn:last-child {
  margin-right: 0;
}

.pagination-section {
  padding: 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #ebeef5;
}

.attribute-form {
  padding: 20px 0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .search-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input,
  .type-select {
    width: 100%;
  }
}
</style>
